package com.imist.nettybasic4.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class IMIdleStateHandler extends IdleStateHandler {
    private static final int READER_IDLE_TIME = 20 ;
    public IMIdleStateHandler() {
        /**
         * 读空闲时间
         * 写空闲时间 这里填0 代表不关心写
         * 读写空闲时间
         */
        super(READER_IDLE_TIME, 0, 0, TimeUnit.SECONDS);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        System.out.println("异常关闭连接...");
        Channel channel = ctx.channel();
        if (channel.isActive()) channel.close();
    }

    @Override
    protected IdleStateEvent newIdleStateEvent(IdleState state, boolean first) {
        return super.newIdleStateEvent(state, first);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        System.out.println(READER_IDLE_TIME+"秒内未读到数据，关闭连接");
        ctx.channel().close();
        //可以在这里实现重连机制，空闲多少次，发起重连策略，或者在 IdleStateEvent 检测到相应的空闲时间然后做出重连机制
    }


}
